//
//  DeviceDetailController.m
//  DYLYJ
//
//  Created by JM on 15/10/23.
//  Copyright © 2015年 JM. All rights reserved.
//

#import "DeviceDetailController.h"
#import "DYUIKit.h"
#import <Masonry.h>
#import <AVFoundation/AVFoundation.h>
#import <QuartzCore/QuartzCore.h>
#import "DevieEditController.h"
#import "DeviceDetailFeature1Cell.h"f
#import "DeviceDetailFeature2Cell.h"
#import <YYCategories.h>
#import "DYRequestAll.h"
#import "AppDelegate.h"
#import "DYServer.h"
#import <ReactiveCocoa.h>
#define DATA_CMD                        @"cmd"
@interface DeviceDetailController ()<UITableViewDelegate, UITableViewDataSource>
@property(nonatomic, assign) BOOL isNormal;
@property(nonatomic, strong) NSMutableArray *cells;
@property(nonatomic, strong) DeviceCell *devieceCell;
@property(nonatomic, strong) DeviceDetailFeature1Cell *devieceControlFeature1Cell;
@property(nonatomic, strong) DeviceDetailFeature2Cell *devieceControlFeature2Cell;
@end

@implementation DeviceDetailController

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
     self.device.deleagete=self;
}
-(void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
     self.device.deleagete=nil;
}

- (void)clickBackBtn:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"晾衣架";
    
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem backBarItemWithTarget:self action:@selector(clickBackBtn:)];
//    self.view.backgroundColor = ;
//    UIBarButtonItem *rightBarButtonItem1 = [UIBarButtonItem barItemWithImageName:@"settingBtn" Target:self action:@selector(clickChangeShowType:)];
    UIBarButtonItem *rightBarButtonItem2 = [UIBarButtonItem barItemWithImageName:@"settingBtn" Target:self action:@selector(clickSetting:)];
    
    self.navigationItem.rightBarButtonItems = @[rightBarButtonItem2];
    
    self.devieceCell = [DeviceCell cell];
    [self.devieceCell setDevice:self.device];
    self.devieceCell.delegate = self;
    
    self.devieceControlFeature1Cell = [DeviceDetailFeature1Cell cell];
    self.devieceControlFeature2Cell = [DeviceDetailFeature2Cell cell];
    self.devieceControlFeature2Cell.delegate = self;
    
    self.devieceControlFeature1Cell.device = self.device;
    self.devieceControlFeature1Cell.device = self.device;
    self.devieceControlFeature1Cell.delegate = self;

    self.cells = [NSMutableArray arrayWithObjects:self.devieceCell,self.devieceControlFeature1Cell,nil];
    self.isNormal = YES;
    self.tableView.scrollEnabled = NO;
    
    if (myAppDelegate.isDemo)
        return;
    if (!self.device.xpgDevice &&(!myAppDelegate.isDemo)){
        [MJAlertView showAlertViewWithTitle:@"温馨提示" message:@"存在伪造数据" clickedButtonBlock:^(NSInteger index) {
//            [self.device.xpgDevice disconnect];
            [self.navigationController popViewControllerAnimated:YES];
        } cancelButtonTitle:@"确定" otherButtonTitles:nil];
//        [MJAlertView showMessage:@"存在伪造数据"];
        return;
    }
    
    if (!self.device.xpgDevice.isOnline&&(!myAppDelegate.isDemo)){
        [MJAlertView showAlertViewWithTitle:@"温馨提示" message:@"设备不在线，请上线后刷新设备列表" clickedButtonBlock:^(NSInteger index) {
//            [self.device.xpgDevice disconnect];
            [self.navigationController popViewControllerAnimated:YES];
        } cancelButtonTitle:@"确定" otherButtonTitles:nil];
    }
    
    
    //如果没有设置委托，则设置委托到当前使用的Cocoa类所对应的实例
    self.device.deleagete = self;
    
    if (!self.device.xpgDevice.isConnected){
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        //需要开发者自行把 uid 和 token 换成实际的值
        [self.device.xpgDevice login:myAppDelegate.uid token:myAppDelegate.token];
    }else {
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        self.device.deleagete = self;
        NSLog(@"发读指令");
        [self.device.xpgDevice write:@{DATA_CMD: @(2)}];//读所有数据
    }
    
}
- (void)XPGWifiDevice:(XPGWifiDevice *)device didLogin:(int)result {
    if ([self.device.macAddress isEqualToString:device.macAddress]){
        self.devieceCell.device.xpgDevice = device;
        [self.devieceCell update];
    }
    if(result == XPGWifiError_NONE) {
//        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        self.device.deleagete = self;
        [self.device.xpgDevice write:@{DATA_CMD: @(2)}];//读所有数据
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [MBProgressHUD hideHUDForView:self.view animated:YES];
//        });
        
        NSLog(@"设备登陆成功");
    }
    else
    {
        [MJAlertView showAlertViewWithTitle:@"温馨提示" message:[NSError dy_errorWithErrCode:result].dy_description clickedButtonBlock:^(NSInteger index) {
            [self.device.xpgDevice disconnect];
            [self.navigationController popViewControllerAnimated:YES];
        } cancelButtonTitle:@"确定" otherButtonTitles:nil];
    }
}

- (IBAction)swipeLeft:(id)sender {
    if (self.isNormal == NO) {
        return;
    }
    [self clickChangeShowType:nil];
}
- (IBAction)swipeRight:(id)sender {
    if (self.isNormal == YES) {
        return;
    }
    [self clickChangeShowType:nil];
}

- (void)clickChangeShowType:(id)sender {
    if (self.isNormal == NO) {
        self.isNormal = YES;
        self.cells = [NSMutableArray arrayWithObjects:self.devieceCell,self.devieceControlFeature1Cell,nil];
        [self.tableView updateWithBlock:^(UITableView *tableView) {
            [self.tableView reloadRow:1 inSection:0 withRowAnimation:UITableViewRowAnimationRight];
            [self.devieceCell setDevice:self.device];
            [self.devieceControlFeature1Cell setDevice:self.device];
            [self.devieceControlFeature2Cell setDevice:self.device];
        }];
    } else {
         self.isNormal = NO;
        self.cells = [NSMutableArray arrayWithObjects:self.devieceCell,self.devieceControlFeature2Cell,nil];
        [self.tableView updateWithBlock:^(UITableView *tableView) {
            [self.tableView reloadRow:1 inSection:0 withRowAnimation:UITableViewRowAnimationLeft];
            [self.devieceCell setDevice:self.device];
            [self.devieceControlFeature1Cell setDevice:self.device];
            [self.devieceControlFeature2Cell setDevice:self.device];
            if (self.device.isStop_On){
                self.devieceControlFeature2Cell.perfentLabel.text = @"停";
            }else if (self.device.isOpen_On){
                self.devieceControlFeature2Cell.perfentLabel.text = @"开";
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.devieceControlFeature2Cell moveOffset:1 withDuration:1 animated:NO];
                });
                
            }else if (self.device.isClose_On){
                self.devieceControlFeature2Cell.perfentLabel.text = @"关";
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.devieceControlFeature2Cell moveOffset:0 withDuration:1 animated:NO];
                });
            }

        }];
    }
//        [self.tableView reloadData];
}
- (void)clickSetting:(id)sender {
    UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    DevieEditController* vc = [storyboard instantiateViewControllerWithIdentifier:@"DevieEditController"];
    vc.device = self.device;
    vc.editblock = ^(Device * aNewDevice){
        self.device = aNewDevice;
        self.devieceCell.device = self.device;
//        [self.tableView updateWithBlock:^(UITableView *tableView) {
//            [self.tableView reloadRow:0 inSection:0 withRowAnimation:UITableViewRowAnimationMiddle];
//        }];
    };
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath; {
    
    // Remove seperator inset
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    // Prevent the cell from inheriting the Table View's margin settings
    if ([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
        [cell setPreservesSuperviewLayoutMargins:NO];
    }
    
    // Explictly set your cell's layout margins
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }

    
    for (id currentView in cell.subviews) {
        if ([NSStringFromClass([currentView class]) isEqualToString:@"UITableViewCellScrollView"]) {
            if ([currentView isKindOfClass:[UIScrollView class]]) {
                [(UIScrollView *)currentView setDelaysContentTouches:NO];\
                 break;
            }
        }
    }
}

//- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
//{
//    
//     NSLog(@"点击");
//    UITouch *t = [touches anyObject];
//    CGPoint location = [t locationInView:self.viewBottom];
//
//    CGFloat xChange = [self.viewBottom.layer.presentationLayer frame].origin.x - self.viewBottom.layer.frame.origin.x;
//    CGFloat yChange = [self.viewBottom.layer.presentationLayer frame].origin.y - self.viewBottom.layer.frame.origin.y;;
//    CGRect rc = [self.button.layer convertRect:self.button.layer.bounds toLayer:self.viewBottom.layer];
//    rc.origin.x += xChange;
//    rc.origin.y += yChange;
//    if (CGRectContainsPoint(rc, location)) {
//        NSLog(@"击中");
//         [self.upDownStopPlayer play];
//        [self.viewBottom.layer removeAllAnimations];
//        CGFloat yChange = [self.viewBottom.layer.presentationLayer frame].origin.y - self.viewBottom.layer.frame.origin.y;;
//        CGFloat percent =  yChange/(self.startBottom -self.endBottom);
//        if (self.endBottom == self.viewBottom.bottom) {//目标是顶部状态
//            percent =  1-percent;
//        } else {
//            percent =  -percent;
//        }
//        self.currentPercent = percent;
//        [self moveOffset:self.currentPercent withDuration:0.2 animated:NO];
//        [self.timer invalidate];//解决停止后 百分比为0的情况
//    }
//    
//}

#pragma mark-tableview

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.cells.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [self.cells[indexPath.row] contentView].userInteractionEnabled = YES;
    return self.cells[indexPath.row];

}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    MDYCell *cell = self.cells[indexPath.row];
    return [cell height];
}

#pragma mark-
#define DATA_header                     @"cmd"              //命令
#define DATA_body                       @"entity0"               //实体

//#define DATA_ATTR_SWITCH                @"Switch"                //属性：开关
#define DATA_ATTR_UP                    @"Open_On"             //属性：上
#define DATA_ATTR_DOWN                  @"Close_On"            //属性：下
#define DATA_ATTR_STOP                  @"Stop_On"            //属性：停
#define DATA_ATTR_Light                 @"LED_OnOff"            //属性：照明开关
#define DATA_ATTR_XD                    @"Xiaodu_OnOff"      //属性：消毒开关
#define DATA_ATTR_HongGan               @"Honggan_OnOff" //属性：烘干
#define DATA_ATTR_FengGan               @"Fenggan_OnOff" //属性：风干
#define DATA_ATTR_Power               @"Auto_OnOff" //属性：电源开关


- (void)didDeviceClickCmd:(TDeviceCmdType) aCmd; {
    
    if (myAppDelegate.isDemo){
        
        switch (aCmd) {
                
            case DevieClickCmdPowerOn:
            {
                
                self.device.isPower_on = YES;
            }
                break;
            case DevieClickCmdPowerOff:
            {
              self.device.isPower_on = NO;
            }
                 break;
            case DevieClickCmdUp:
            {
                
                self.device.isOpen_On = YES;
                self.device.isClose_On = NO;
                self.device.isStop_On = NO;
//                self.device.open = YES;
            }
                break;
            case DevieClickCmdDown:
            {
               
                self.device.isClose_On = YES;
                self.device.isStop_On = NO;
                self.device.isOpen_On = NO;
//                 self.device.open = NO;
            }
                break;
            case DevieClickCmdStop:
            {
                self.device.isStop_On = YES;
                self.device.isOpen_On = NO;
                self.device.isClose_On = NO;
            }
                break;
            case DevieClickCmdLight:
            {
                self.device.isLED_On = !self.device.isLED_On;
            }
                break;
            case DevieClickCmdXD:
            {
                self.device.isXiaodu_On = !self.device.isXiaodu_On;
            }
                break;
            case DevieClickCmdHongGan:
            {
                self.device.isHonggan_On = !self.device.isHonggan_On;
                if (self.device.isHonggan_On){
                    self.device.isFenggan_On = YES;
                }
            }
                break;
            case DevieClickCmdFengGan:
            {
                self.device.isFenggan_On = !self.device.isFenggan_On;
                if (self.device.isHonggan_On){
                    self.device.isFenggan_On = YES;
                }
            }
                break;
                
            default:
                break;
        }
        [self.devieceCell setDevice:self.device];
        [self.devieceControlFeature1Cell setDevice:self.device];
        [self.devieceControlFeature2Cell setDevice:self.device];
        if (self.device.isStop_On){
            self.devieceControlFeature2Cell.perfentLabel.text = @"停";
        }else if (self.device.isOpen_On){
            self.devieceControlFeature2Cell.perfentLabel.text = @"开";
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.devieceControlFeature2Cell moveOffset:1 withDuration:1 animated:NO];
            });
            
        }else if (self.device.isClose_On){
            self.devieceControlFeature2Cell.perfentLabel.text = @"关";
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.devieceControlFeature2Cell moveOffset:0 withDuration:1 animated:NO];
            });
        }
        return;
    }
    //------------------
    NSDictionary *cmdDic = nil;
    switch (aCmd) {
        case DevieClickCmdPowerOn:
        {
            cmdDic = @{DATA_header: @(1),//写 还有读等？
                       DATA_body: @{DATA_ATTR_Power: @(YES)}
                       };
        }
            break;
        case DevieClickCmdPowerOff:
        {
            cmdDic = @{DATA_header: @(1),//写 还有读等？
                       DATA_body: @{DATA_ATTR_Power: @(NO)}
                       };
        }
            break;

        case DevieClickCmdUp:
        {
            cmdDic = @{DATA_header: @(1),//写 还有读等？
                       DATA_body: @{DATA_ATTR_UP: @(YES)}
                       };;
        }
            break;
        case DevieClickCmdDown:
        {
            cmdDic = @{DATA_header: @(1),//写 还有读等？
                       DATA_body: @{DATA_ATTR_DOWN: @(YES)
                                   }
                       };;
        }
            break;
        case DevieClickCmdStop:
        {
            cmdDic = @{DATA_header: @(1),//写 还有读等？
                       DATA_body: @{DATA_ATTR_STOP: @(!self.device.isStop_On)}};;
        }
            break;
        case DevieClickCmdLight:
        {
            cmdDic = @{DATA_header: @(1),//写 还有读等？
                       DATA_body: @{DATA_ATTR_Light: @(!self.device.isLED_On)}};;
        }
            break;
        case DevieClickCmdXD:
        {
            cmdDic = @{DATA_header: @(1),//写 还有读等？
                       DATA_body: @{DATA_ATTR_XD: @(!self.device.isXiaodu_On)}};;
        }
            break;
        case DevieClickCmdHongGan:
        {
            cmdDic = @{DATA_header: @(1),//写 还有读等？
                       DATA_body: @{DATA_ATTR_HongGan: @(!self.device.isHonggan_On)}};;
        }
            break;
        case DevieClickCmdFengGan:
        {
            cmdDic = @{DATA_header: @(1),//写 还有读等？
                       DATA_body: @{DATA_ATTR_FengGan: @(!self.device.isFenggan_On)}};;
        }
            break;
            
        default:
            break;
    }
    self.device.deleagete = self;
    
    if (![self.device.xpgDevice.macAddress isEqualToString:@"VIRTUAL:SITE"]) {
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    }
    
    NSLog(@"发送命令%@",cmdDic);
    [self.device.xpgDevice write:cmdDic];
    [self.devieceCell setDevice:self.device];
//    [self.devieceControlFeature1Cell setDevice:self.device];
//    [self.devieceControlFeature2Cell setDevice:self.device];
}

- (void)XPGWifiDevice:(XPGWifiDevice *)device didReceiveData:(NSDictionary *)data result:(int)result {
    dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    });

     NSLog(@"收到到数据:%@",data);
    
    if (result !=  XPGWifiError_NONE) {
        [MJAlertView showMessage:[NSError dy_errorWithErrCode:result].dy_description];
        NSLog(@"命令处理失败:%d",result);
        return;
    }
    
    //基本数据，与发送的数据格式⼀一致
    NSDictionary *_data = [data valueForKey:@"data"];
//    //警告
//    NSArray *alarms = [data valueForKey:@"alarms"];
//    //错误
//    NSArray *faults = [data valueForKey:@"faults"];
//    //透传数据
//    NSDictionary *binary = [data valueForKey:@"binary"];
   
    if (_data) {
        [self.devieceCell setDevice:self.device];
        [self.devieceControlFeature1Cell setDevice:self.device];
        [self.devieceControlFeature2Cell setDevice:self.device];
    }
}

//- (void)XPGWifiDeviceDidDisconnected:(XPGWifiDevice *)device result:(int)result {
//    if ([self.device.macAddress isEqualToString:device.macAddress]){
//         [self.device setXpgDevice:device];
//        [MJAlertView showMessage:@"断开连接"];
//    }
//}
- (void)XPGWifiDeviceDidDisconnected:(XPGWifiDevice *)device result:(int)result {
    dispatch_async(dispatch_get_main_queue(), ^{
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    });
    if([device.macAddress isEqualToString:self.device.macAddress]){
        [MJAlertView showMessage:[NSString stringWithFormat:@"%@断开连接",self.device.name]];
    }
//    Device *dydevice= [self itemWithMacAdress:device.macAddress];
//    [dydevice setXpgDevice:device];
//    NSLog(@"did%@：断开连接%d",device.did,result);
//    id delegate = [self delegateOfDevice:device];
//    if (delegate && [delegate respondsToSelector:@selector(XPGWifiDeviceDidDisconnected: result:)]){
//        [delegate XPGWifiDeviceDidDisconnected:device result:result];
//    }
}
@end
